import os
import glob
from openai import OpenAI

client = OpenAI(
    base_url='https://api-inference.modelscope.cn/v1/',
    api_key="API_KEY", # ModelScope Token
)

# 设置模型思考模式
extra_body = {
    # 启用或禁用思考
    "enable_thinking": False,
    # 思考token限制
    # "thinking_budget": 4096
}

def read_custom_file(filepath):
    """读取自定义格式变更日志文件"""
    with open(filepath, 'r', encoding='utf-8') as f:
        return f.read()


def generate_summary(content):
    """使用大模型生成版本变更总结"""
    response = client.chat.completions.create(
        model='Qwen/Qwen3-32B',  
        messages=[
            {"role": "system", "content": "你是一个技术文档工程师，擅长总结版本变更"},
            {"role": "user", "content": f"分析以下版本变更日志，总结一段版本变更说明：\n{content}"}
        ],
        stream=False,
        extra_body=extra_body
    )
    return response.choices[0].message.content


def process_diff_files(data_dir="data/"):
    """处理/data目录下所有_diff前缀文件"""
    for diff_file in glob.glob(os.path.join(data_dir, "*_diff*")):
        # 生成对应的summary文件名
        base_name = os.path.basename(diff_file)
        summary_name = base_name.replace("_diff", "_summary")
        summary_path = os.path.join(data_dir, summary_name)

        # 跳过已存在的summary文件
        if os.path.exists(summary_path):
            continue

        # 读取原始变更日志
        with open(diff_file, 'r', encoding='utf-8') as f:
            content = f.read()

        # 生成总结并写入新文件
        summary = generate_summary(content)
        with open(summary_path, 'w', encoding='utf-8') as f:
            f.write(summary)
            print('summary:', summary)

        print(f"已生成: {summary_name}")


if __name__ == "__main__":
    process_diff_files()
